<template>
  <div class="compact-container">
    <!-- Compact search row with buttons on the right -->
    <div class="search-row">
      <span class="search-label">产品分类名称：</span>
      <!-- <el-input v-model="proName" size="small" class="search-input" />
      <span class="search-label">产品分类：</span>
      <el-tree-select size="small"
        v-model="typeCode" 
        :data="data" 
        placeholder="产品分类" 
        class="tree-select"
        :props="treeProps" 
        clearable 
        check-strictly 
      /> -->
      <el-input v-model="proName" class="search-input" size="small" />
      <span class="search-label">产品分类：</span>
      <el-tree-select v-model="typeCode" :data="data" placeholder="产品分类" class="tree-select" :props="treeProps"
        clearable check-strictly size="small" />
      <el-button type="primary" size="small" @click="query">查询</el-button>
      <el-button size="small" @click="reset">重置</el-button>
      <div class="flex-grow"></div>
      <el-button type="primary" size="small" @click="exportToExcel">导出</el-button>
      <el-button type="primary" size="small" @click="addEdit">添加</el-button>
    </div>

    <el-divider style="margin: 6px 0" />

    <!-- Compact layout with tree and table -->
    <div class="layout-container">
      <div class="tree-wrapper">
        <el-tree :data="data" :props="defaultProps" @node-click="handleNodeClick"
          style="height: calc(100vh - 220px); overflow: auto" />
      </div>

      <div class="table-wrapper">
        <el-table :data="tableData" border style="width: 100%" :cell-style="{ textAlign: 'center' }" :header-cell-style="{
          textAlign: 'center',
          background: '#f5f7fa',
          fontWeight: 'bold',
          position: 'sticky',
          top: 0
        }" ref="customerTable">
          <el-table-column prop="pro_code" label="产品编号" fixed="left" width="180px">
            <template #default="scope">
              <el-link type="primary" @click="infoPage(scope.row.pro_code)">{{ scope.row.pro_code
              }}</el-link>
            </template>
          </el-table-column>

          <el-table-column prop="pro_name" label="产品名称" width="120px" fixed="left" />

          <el-table-column prop="pro_status" label="状态" width="100px">
            <template #default="scope">
              <span>{{ scope.row.pro_status == 0 ? "正常" : "停用" }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="pro_sort" label="排序" width="80" />

          <el-table-column prop="pro_type_code" label="产品类型" width="150px">
            <template #default="scope">
              <span>{{ typeValue(scope.row.pro_type_code) }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="pro_model" label="规格型号" width="150px" />

          <el-table-column prop="pro_attribute" label="产品属性" width="120px">
            <template #default="scope">
              <span>{{ attributeValue(scope.row.pro_attribute_id) }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="measure_id" label="单位" width="100px">
            <template #default="scope">
              <span>{{ measureValue(scope.row.measure_id) }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="pro_shelf_life" label="保质期" width="170px">
            <template #default="scope">
              <span>{{ scope.row.pro_shelf_life + '天' }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="pro_cost_price" label="成本单价" width="120px" />
          <el-table-column prop="pro_sale_price" label="标准售价" width="120px" />

          <el-table-column label="操作" fixed="right" width="180px">
            <template #default="scope">
              <el-button size="small" @click="handleEdit(scope.row.pro_code)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-center">
          <el-pagination small v-model:current-page="currentPage" v-model:page-size="pageSize"
            :page-sizes="[5, 10, 20, 50]" :background="true" layout="total, sizes, prev, pager, next, jumper"
            :total="pageCount" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, markRaw, toRaw } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import { useStore } from 'vuex'

export default {
  setup() {
    const router = useRouter()
    const store = useStore()
    const tableData = ref()
    const currentPage = ref(1)
    const pageSize = ref(10)
    const pageCount = ref(0)
    const attributeOptios = ref([])
    const measureOptios = ref([])
    const data = ref([])
    const proName = ref("")
    const typeCode = ref("")
    const customerTable = ref(null)

    onMounted(() => {
      pro_type_Opt()
      getAttribute()
      getMeasure()
      fill()
      count()
    })

    function pro_type_Opt() {
      axios.get("http://localhost:5181/api/Product_Type/GetProduct_Types", {
        params: {
          currentPage: 0,
          pageSize: 0,
          typeName: "",
          status: '0'
        },
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        data.value = convertToTreeOptions(result.data)
        console.info(data.value)
      }).catch((err) => {
        console.error(err)
      })
    }

    const convertToTreeOptions = (items) => {
      return items.map(item => ({
        value: item.pro_type_code,
        pro_type_code: item.pro_type_code,
        label: item.pro_type_name,
        children: item.children && item.children.length > 0
          ? convertToTreeOptions(item.children)
          : []
      }))
    }

    function fill() {
      axios.get("http://localhost:5181/api/Db_Product/Get_Products", {
        params: {
          proName: proName.value,
          typeCode: typeCode.value,
          currentPage: currentPage.value,
          pageSize: pageSize.value
        },
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        // tableData.value = result.data
        tableData.value = result.data.map(item => {
          // 1. 若整个item为空（null/undefined），返回"暂无"
          if (item == null) return '暂无';

          // 2. 若item是对象，则遍历其属性，替换空值为"暂无"
          if (typeof item === 'object' && item !== null) {
            return Object.fromEntries(
              Object.entries(item).map(([key, value]) => [
                key,
                // 检测空字符串、null、undefined、纯空格
                value == null || (typeof value === 'string' && value.trim() === '')
                  ? '暂无'
                  : value
              ])
            );
          }

          // 3. 非对象类型直接返回（如原始值）
          return item;
        });
      }).catch((err) => {
        console.error(err)
      })
    }

    function count() {
      axios.get("http://localhost:5181/api/Db_Product/ProductCount", {
        params: {
          proName: proName.value,
          typeCode: typeCode.value
        },
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        pageCount.value = result.data
      }).catch((err) => {
        console.error(err)
      })
    }

    function typeValue(row) {
      if (!row || !data.value) return "无"; // 空值保护

      // 假设 row 是一个对象，包含 pro_type_code 字段
      const typeCode = row;


      // 递归查找匹配的项
      const findLabel = (items) => {
        // console.info(items)
        // console.info(typeCode)
        for (const item of items) {
          if (item.pro_type_code === typeCode) {
            return item.label;
          }
          if (item.children && item.children.length > 0) {
            const found = findLabel(item.children);
            if (found) return found;
          }
        }
        return null;
      };

      const label = findLabel(data.value);
      return label || "未知类型"; // 如果没找到返回默认值
    }

    function getAttribute() {
      axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
        params: {
          dict_type: "db_pro_attribute"
        },
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        attributeOptios.value = result.data
      }).catch((err) => {
        console.error(err)
      })
    }

    function attributeValue(row) {
      if (!row) return "无"
      const parentDept = attributeOptios.value.find((sex) => sex.dict_value == row)
      return parentDept ? parentDept.dict_label : "无"
    }

    function getMeasure() {
      axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
        params: {
          dict_type: "db_measure"
        },
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        measureOptios.value = result.data
      }).catch((err) => {
        console.error(err)
      })
    }

    function measureValue(row) {
      if (!row) return "无"
      const parentDept = measureOptios.value.find((sex) => sex.dict_value == row)
      return parentDept ? parentDept.dict_label : "无"
    }

    function query() {
      fill()
      count()
    }

    function reset() {
      proName.value = ""
      typeCode.value = ""
      fill()
      count()
    }

    function handleNodeClick(data, node, e) {
      typeCode.value = data.value
      query()
    }

    function addEdit() {
      router.push("/main/DB/ProductAdd")
    }

    function handleSizeChange(val) {
      pageSize.value = val
      fill()
    }

    function handleCurrentChange(val) {
      currentPage.value = val
      fill()
    }

    function handleDelete(row) {
      ElMessageBox.confirm(
        '此操作将删除' + row.pro_name + '产品信息，是否继续？',
        '警告',
        {
          type: 'warning',
          icon: markRaw(Delete),
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }
      )
        .then(() => {
          const loadingInstance = ElLoading.service({
            lock: true,
            text: '正在删除中...',
            background: 'rgba(0, 0, 0, 0.7)',
          });
          axios.put("http://localhost:5181/api/Db_Product/ProductDel", {
            pro_id: row.pro_id,
            del_flag: '1'
          }, {
            headers: {
              authorization: `Bearer ${localStorage.getItem('token')}`
            }
          }).then((result) => {
            if (result.data > 0) {
              ElMessage.success('删除成功！')
              fill()
              count()
            }
          }).catch((err) => {
            console.error(err)
          }).finally(() => {
            loadingInstance.close();
          })
        })
        .catch(() => {
          ElMessage.info('已取消删除')
        })
    }

    function handleEdit(row) {
      store.commit('proCode', row)
      router.push('/main/DB/ProductUpdate')
    }

    function infoPage(row) {
      store.commit('proCode', row)
      router.push('/main/DB/ProductInfoPage')
    }

    function getTableHeaders() {
      if (customerTable.value) {
        const filteredColumns = customerTable.value.columns.filter(column => {
          return column.label !== '操作'
        })
        const headers = filteredColumns.map(column => column.label)
        return headers
      }
      return []
    }

    const exportToExcel = async () => {
      const headers = getTableHeaders()
      const row = toRaw(tableData.value)
      const headerMap = {
        '产品编号': 'pro_code',
        '产品名称': "pro_name",
        '状态': 'pro_status',
        '排序': 'pro_sort',
        '产品类型': 'pro_type_code',
        '规格型号': 'pro_model',
        '产品属性': 'pro_attribute_id',
        '单位': 'measure_id',
        '保质期': 'pro_shelf_life',
        '成本单价': 'pro_cost_price',
        '标准售价': 'pro_sale_price'
      }

      const rowDataArray = row.map(item => {
        return headers.map(header => {
          const propName = headerMap[header]
          if (propName === "pro_status") {
            item[propName] = item[propName] == 0 ? "正常" : "停用"
          } else if (propName === "pro_type_code") {
            item[propName] = typeValue(item[propName])
          } else if (propName === "pro_attribute_id") {
            item[propName] = attributeValue(item[propName])
          } else if (propName === "measure_id") {
            item[propName] = measureValue(item[propName])
          }
          return item[propName]
        })
      })

      try {
        const response = await axios.post('http://localhost:5181/api/SystemHome/ExportExcel', {
          headers: headers,
          rows: rowDataArray,
          title: "产品信息"
        }, {
          responseType: 'blob'
        })

        const url = window.URL.createObjectURL(new Blob([response.data]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', '产品信息.xlsx')
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
      } catch (error) {
        console.error('导出 Excel 失败:', error)
      }
    }

    return {
      data, tableData, currentPage, pageSize, pageCount, typeValue, attributeValue, measureValue,
      attributeOptios, measureOptios, typeCode, proName, query, reset, handleNodeClick, addEdit,
      handleSizeChange, handleCurrentChange, handleDelete, handleEdit, infoPage, customerTable,
      exportToExcel
    }
  }
}
</script>

<style scoped>
.compact-container {
  padding: 10px;
}

.search-row {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 6px;
  margin-top: -40px;
}

.search-label {
  white-space: nowrap;
  font-size: 13px;
}

.search-input {
  width: 160px !important;
}

.tree-select {
  width: 160px !important;
  margin-right: 6px;
}

.flex-grow {
  flex-grow: 1;
}

.layout-container {
  display: flex;
  gap: 10px;
  height: calc(100vh - 180px);
}

.tree-wrapper {
  width: 150px;
  background: #fff;
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-wrapper {
  flex: 1;
  background: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 10px;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  max-width: 90%;
}

.pagination-center {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.action-group {
  display: flex;
  justify-content: center;
  gap: 4px;
}

:deep(.el-table__row) {
  height: 36px !important;
}

:deep(.el-table th.el-table__cell) {
  height: 36px !important;
}

:deep(.el-button--small) {
  padding: 5px 8px;
  height: 24px;
}

@media (max-width: 992px) {
  .layout-container {
    flex-direction: column;
    height: auto;
  }

  .tree-wrapper {
    width: 100%;
    margin-bottom: 10px;
  }
}
</style>